﻿using AutoMapper;
using Domain.Process_Procedures;
using Domain.User;
using Infratructure.Implement;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Process_Procedures.ProcessFlow;
using MES.Server.API.Dto.ProcessProceduresDTO;
using Microsoft.EntityFrameworkCore;
using ReturnValue;
using System.Diagnostics;

namespace MES.Server.API.Application.Handler.Process_Procedures.ProcessFlow
{
    public class CheckProcessFlowHandler : IRequestHandler<CheckProcessFlowCommand, ApiResult<ProcessFlowDetailDto>>
    {
        private readonly IRepository<ProcessFlowModel> _processFlowRepo;
        private readonly IRepository<ProcessFlowDetailModel>_processFlowDetailRepo;
        private readonly IRepository<ProcessManagementModel> _processManagementRepo;
        private readonly IRepository<AccountModel> _personService;
        private readonly IRepository<DepartmentModel> _departmentService;
        private readonly IMapper _mapper;

        public CheckProcessFlowHandler(
            IRepository<ProcessFlowModel> processFlowRepo, 
            IRepository<ProcessFlowDetailModel> processFlowDetailRepo, 
            IRepository<ProcessManagementModel> processManagementRepo, 
            IRepository<AccountModel> personService, 
            IRepository<DepartmentModel> departmentService, IMapper mapper)
        {
            _processFlowRepo = processFlowRepo;
            _processFlowDetailRepo = processFlowDetailRepo;
            _processManagementRepo = processManagementRepo;
            _personService = personService;
            _departmentService = departmentService;
            _mapper = mapper;
        }

        public async Task<ApiResult<ProcessFlowDetailDto>> Handle(CheckProcessFlowCommand request, CancellationToken cancellationToken)
        {
            // 1. 查询【工艺流程主信息】
            var processFlow = await _processFlowRepo.GetValue(request.FlowId);
            var department = await _departmentService.GetValue(processFlow.DepartmentId);
            var person = await _personService.GetValue(processFlow.PersonId);
            if (processFlow == null)
            {
                return new ApiResult<ProcessFlowDetailDto>().Fail("工艺流程不存在");
            }

            // 2. 查询【工艺流程-工序关联记录】（ProcessFlowDetailModel）
            var flowDetails = await _processFlowDetailRepo.GetAll()
                .Where(d => d.ProcessFlowId == request.FlowId)
                .ToListAsync(cancellationToken);

            // 3. 提取【工序ID列表】
            var processIds = flowDetails.Select(d => d.ProcessId).Distinct().ToList();
            if (!processIds.Any())
            {
                // 无工序时，返回“基础信息+空工序列表”
                var emptyDto = new ProcessFlowDetailDto
                {
                    FlowCode = processFlow.FlowCode,
                    FlowName = processFlow.FlowName,
                    DepartmentName = department?.DepartmentName ?? string.Empty,
                    PersonName = person?.AccountName ?? string.Empty,
                    IsActive = processFlow.IsActive ? "启用" : "禁用",
                    Remarks = processFlow.Remarks,
                    Processes = new List<ProcessDto>()
                };
                return new ApiResult<ProcessFlowDetailDto>().Success("查询成功", emptyDto);
            }

            // 4. 查询【工序详情】（ProcessManagementModel）
            var processes = await _processManagementRepo.GetAll()
                .Where(p => processIds.Contains(p.Id))
                .ToListAsync(cancellationToken);

            // 5. 组装最终DTO（关联部门/人员名称）
            var detailDto = new ProcessFlowDetailDto
            {
                FlowCode = processFlow.FlowCode,
                FlowName = processFlow.FlowName,
                DepartmentName = department?.DepartmentName ?? string.Empty,
                PersonName = person?.AccountName ?? string.Empty,
                IsActive = processFlow.IsActive ? "启用" : "禁用",
                Remarks = processFlow.Remarks,
                Processes = processes.Select(p => new ProcessDto
                {
                    ProcessCode = p.ProcessCode,
                    ProcessName = p.ProcessName,
                    PersonName = department?.DepartmentName ?? string.Empty,
                    DepartmentName = person?.AccountName ?? string.Empty,
                    Remarks = p.Remarks
                }).ToList()
            };

            return new ApiResult<ProcessFlowDetailDto>().Success("查询成功", detailDto);
        }
    }
}
